
import createHistory from 'history/createBrowserHistory';
import { Modal, message } from 'antd';
import axios from 'axios';
import Cookies from 'js-cookie';

const confirm = Modal.confirm;
// 路由跳转拦截函数(跳转提示信息)
const getUserConfirmation = (message, callback) => {
    confirm({
        title: '提示信息',
        content: message,
        onOk() {
            callback(true);
        },
        onCancel(){
            callback(false);
        }
    })
}

let modelRef = null;
const showModal = (msg) => {
    if(modelRef) {
        return;
    }
    modelRef = Modal.warning({
        title: '提示信息',
        content: msg
    });
    setTimeout(function() {
        // 关闭弹窗
        modelRef.destroy();
        modelRef = null;
    }, 1500);
}

//history对象
export const history = createHistory({ getUserConfirmation });

//判断是否登录
export const hasLogin = () => {
    return Cookies.get('isLogin');
}


const filterUrl = ['dueInfoDownLoad', '/order/download', 'riskReviewDownLoad', '/order/customerDownload', '/loan/getRepaymentReport','/loan/getLoanReport','/summaryStatisticReport','/dayRegisterStatisticReport'];

const BASE_URL = '/';
//ajax
axios.defaults.baseURL = BASE_URL;
axios.defaults.headers['Content-Type'] = 'application/json';
// 拦截器实现
axios.interceptors.response.use(function(response) {
    const { data, config: { url } } = response;
    //过滤下载订单接口
    if(filterUrl.find(item => url.indexOf(item) !== -1)) {
        return data;
    }

    if(Number(data.code) !== 200 ) {
        //session过期
        if(Number(data.code) === 400) {
            // showModal('session过期，请重新登录！');
            setTimeout(() => {
                Cookies.remove('isLogin');
                history.push('/login');
            }, 1500);
            return;
        }
        //数据格式{code:500, data:{msg:'aa'}} 或者{code:500,message:'aa'}
        const obj = data.data;
        let msg;
        //{code:500,message:'aa'}这种格式
        if (!obj) {
            msg = data['message'];
        } else {
            if(typeof obj === "string") {
                try {
                    const realObj = JSON.parse(obj);
                    msg = realObj['msg'];
                } catch (e) {
                    msg = '系统错误';
                }
            } else {
                msg = obj['msg'];
            }
        }
        showModal(msg || '系统错误');
    }
    return response['data'];
}, function(error) {
    showModal('系统错误');
    // console.log(error.response)
    return Promise.resolve(error);
});

export { axios };


const covertUrlParams = (url) => {
    if(!url) {
        return {};
    }
    const str = url.replace(/\?/,'');
    const arr = str.split('&');

    return arr.reduce((prev, current) => {
        const paramsArr = current.split('=');
        prev[paramsArr[0]] = paramsArr[1] === undefined ? '' : paramsArr[1];
        return prev;
    },{})
}
export { covertUrlParams }


const orderStatus = {
    0: '未提交',
    1: '已提交未审核',
    2: '初审通过待复审',
    3: '复审中',
    4: '黑名单',
    5: '复审通过待终审',
    6: '终审中',
    7: '被拒',
    8: '终审通过放款中',
    9: '放款成功待还款',
    10: '已结清',
    11: '放款失败',
    12: '已逾期',
    // 13: '已寄手机'
}
export { orderStatus }

const checkRecordStatus = {
    1: '机审通过',
    2: '机审拒绝',
    3: '复审通过',
    4: '复审拒绝',
    5: '复审拉黑',
    6: '终审通过'
};
export { checkRecordStatus };

const showMsg = (msg) => {
    message.success(msg);
}
export { showMsg }

/*
export async function getData(url, method = 'get', params) {
    if (typeof url === 'undefined') {
        throw Error('url is required');
    }
    if(Object.prototype.toString.call(params) !== '[object object]') {
        throw Error('params is object');
    }
    const realUrl = BASE_URL + url;
    let requestMethod;
    const index = ['get', 'post'].indexOf(method.toLowerCase());
    requestMethod = index === -1 ? 'get' : method.toLowerCase();


    const requestOption = {
        url: realUrl,
        method: requestMethod,
        responseType: 'json'
    };
    if (requestMethod === 'get') {
       requestOption['params'] = params;
    }
    if(requestMethod === 'post') {
        requestOption['data'] = params;
    }

    try {
        const response = await axios(requestOption);

    } catch(e) {

    }




}*/
